package game.module.ranking.manager;

import game.constants.GameConstant;
import game.module.ranking.bean.RankingHero;
import game.module.ranking.dao.RankingDao;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Component;

/**
 * 定时更新排行榜
 * 
 * @author hexuhui
 * 
 */
@Component
public class RankingCache {

	private static Logger logger = LoggerFactory.getLogger(RankingCache.class);

	@Autowired
	private CacheManager cacheManager;

	@Autowired
	private RankingDao rankingDao;

	public void timingRefreshRanking() {
		logger.info("refreshRanking");
		refreshGradeRanking();
		refreshCopperRanking();
	}

	private void refreshCopperRanking() {
		List<RankingHero> rankingHeroList = rankingDao.refreshCopperRanking();
		updateCache(rankingHeroList, GameConstant.CACHE_RANKING_COPPER);
	}

	@SuppressWarnings("unchecked")
	private void updateCache(List<RankingHero> rankingHeroList, byte cacheType) {
		Cache cache = cacheManager.getCache(GameConstant.CACHE_RANKING);
		List<RankingHero> oldHeroList = (List<RankingHero>) cache.get(cacheType).get();
		short position = 1;
		for (RankingHero rankingHero : rankingHeroList) {
			rankingHero.setPosition(position);
			for (RankingHero oldHero : oldHeroList) {
				if (rankingHero.getId() == oldHero.getId()) {
					rankingHero.setChangePosition((short) (oldHero.getPosition() - position));
				}
			}
		}
		cache.put(cacheType, rankingHeroList);
	}

	private void refreshGradeRanking() {
		List<RankingHero> rankingHeroList = rankingDao.refreshGradeRanking();
		updateCache(rankingHeroList, GameConstant.CACHE_RANKING_GRADE);
	}

	@SuppressWarnings("unchecked")
	public List<RankingHero> getHeroGradeRanking() {
		Cache cache = cacheManager.getCache(GameConstant.CACHE_RANKING);
		return (List<RankingHero>) cache.get(GameConstant.CACHE_RANKING_GRADE);
	}

	@SuppressWarnings("unchecked")
	public List<RankingHero> getHeroCopperRanking() {
		Cache cache = cacheManager.getCache(GameConstant.CACHE_RANKING);
		return (List<RankingHero>) cache.get(GameConstant.CACHE_RANKING_COPPER);
	}

}
